package com.my_musc_service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.my_musc_service.config.ServerConfig;
import com.my_musc_service.dao.FavoriteDao;
import com.my_musc_service.dao.SharedSongDao;
import com.my_musc_service.dao.SongDao;
import com.my_musc_service.dao.SongListUserDao;
import com.my_musc_service.entity.Favorite;
import com.my_musc_service.entity.SharedSong;
import com.my_musc_service.entity.Song;
import com.my_musc_service.entity.SongListUser;
import com.my_musc_service.service.SongService;
import com.my_musc_service.service.UploadService;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (Song)表服务实现类
 *
 * @author makejava
 * @since 2021-06-10 20:44:49
 */
@Service("songService")
public class SongServiceImpl extends ServiceImpl<SongDao, Song> implements SongService {
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Resource
    private SongDao songDao;
    @Resource
    private SongListUserDao songListUserDao;

    @Resource
    private FavoriteDao favoriteDao;

    @Resource
    private SharedSongDao sharedSongDao;

    @Value("${server.port}")
    private String port;
    //绑定文件上传路径到uploadPath
    @Value("${web.upload-path}")
    private String uploadPath;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private UploadService uploadService;

    public String getUrl() {
        return serverConfig.getUrl();
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Song queryById(Integer id) {
        return this.songDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<Song> queryAllByLimit(int offset, int limit) {
        return this.songDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param song 实例对象
     * @return 实例对象
     */
    @Override
    public Song insert(Song song) {
        this.songDao.insert(song);
        return song;
    }

    /**
     * 修改数据
     *
     * @param song 实例对象
     * @return 实例对象
     */
    @Override
    public Song update(Song song) {
        this.songDao.update(song);
        return this.queryById(song.getId());
    }


    @SneakyThrows
    @Override
    public String updateSongInfo(MultipartFile songFile, MultipartFile lyricFile,MultipartFile coverFile, Song song) {
        List<Song> songList = baseMapper.selectList(new QueryWrapper<Song>().eq("id", song.getId()));
        Integer rows = 0;
        if (CollectionUtils.isNotEmpty(songList)) {
            Song songData = songList.get(0);
            //先把原来的文件删除,信息更新到数据库
            rows = updateSong(songData, songFile, lyricFile,coverFile);
            String name = song.getName();
            if (StringUtils.isNotBlank(name)) {
                songData.setName(name);
            }
            String singer = song.getSinger();
            if (StringUtils.isNotBlank(singer)) {
                songData.setSinger(singer);
            }
            String descript = song.getDescript();
            if (StringUtils.isNotBlank(descript)) {
                songData.setDescript(descript);
            }
            //重新上传，里面有批量保存或更新
            String upload = uploadService.upload(songFile, lyricFile,coverFile, songData, null);
//            Song songNew = baseMapper.selectOne(new QueryWrapper<>(songData));
            String lyric = songData.getLyric();
            if (StringUtils.isNotBlank(lyric)) {
                return lyric;
            }

        }
        return null;
    }

    @Override
    public Integer updateSong(Song song, MultipartFile songFile, MultipartFile lyricFile,MultipartFile coverFile) {
        List<Song> songList = songDao.queryAll(song);
        Integer rows = 0;
        if (CollectionUtils.isNotEmpty(songList)) {
            Song songData = songList.get(0);
            //删除歌曲文件
            String url = songData.getUrl();
            if (songFile != null && StringUtils.isNotBlank(url)) {
                deleteSongFile(url);
            }
            //删除歌词文件
            String lyric = songData.getLyric();
            if (lyricFile != null && StringUtils.isNotBlank(lyric)) {
                deleteLyricFile(lyric);
            }
            //删除歌单封面
            String coverUrl = songData.getCoverUrl();
            if (coverFile != null && StringUtils.isNotBlank(coverUrl)) {
                deleteCoverFile(coverUrl);
            }
//            rows = baseMapper.update(song);
        }

        return rows;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.songDao.deleteById(id) > 0;
    }

    @Override
    public Integer deleteBySongList(List<Song> songList) {
        Integer rows = 0;
        if (CollectionUtils.isNotEmpty(songList)) {
            List<Song> songListFromDataList = songList.stream()
                    .map(song -> {
                        List<Song> songListData = baseMapper.selectList(new QueryWrapper<>(song));
                        return songListData.get(0);
                    })
                    .collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(songListFromDataList)) {
                //删除文件
                for (Song song : songListFromDataList) {
                    deleteBySong(song);
                }
                List<Integer> songIds = songListFromDataList.stream().map(Song::getId).collect(Collectors.toList());
                rows = baseMapper.deleteBatchIds(songIds);
            }
        }
        return rows;
    }

    @Override
    public Integer deleteBySong(Song song) {
        List<Song> songList = songDao.queryAll(song);
        Integer rows = 0;
        if (CollectionUtils.isNotEmpty(songList)) {
            Song songData = songList.get(0);
            //删除歌曲文件
            deleteSongFile(songData.getUrl());
            //删除歌词文件
            deleteLyricFile(songData.getLyric());
            rows = deleteSongDataBase(songData);
        }

        return rows;
    }

    private void deleteLyricFile(String lyricUrl) {
        //删除歌词
        //兼容版本
        if (StringUtils.isNotBlank(lyricUrl)) {
            String lyricUri = getFileUri(lyricUrl);
            String lyricPath = uploadPath + "/" + lyricUri;
            File lyricFile = new File(lyricPath);
            if (lyricFile.exists()) {
                lyricFile.delete();
            }
        }
    }

    private void deleteSongFile(String songUrl) {
        //删除歌曲
        //兼容，以前的不规范的
        if (StringUtils.isNotBlank(songUrl)) {
            String songUri = getFileUri(songUrl);
            String songPath = uploadPath + "/" + songUri;
            File songFile = new File(songPath);
            if (songFile.exists()) {
                songFile.delete();
            }
        }
    }

    private void deleteCoverFile(String coverUrl) {
        //删除歌词
        //兼容版本
        if (StringUtils.isNotBlank(coverUrl)) {
            String coverUri = getFileUri(coverUrl);
            String coverPath = uploadPath + "/" + coverUri;
            File coverFile = new File(coverPath);
            if (coverFile.exists()) {
                coverFile.delete();
            }
        }
    }

    private String getFileUri(String url) {
        String uri = null;
        if (url.contains("music")) {
            uri = url.substring(url.lastIndexOf("music") + 6);
        } else {
            uri = url.substring(url.lastIndexOf("9000") + 5);
        }
        return uri;
    }


    private Integer deleteSongDataBase(Song songData) {
        Integer rows;
        //删除数据库歌曲
        rows = songDao.deleteById(songData.getId());
        //删除所有歌单中当前个的关联信息
        SongListUser songListUser = new SongListUser();
        songListUser.setSongId(songData.getId());
        songListUserDao.deleteBySongListUser(songListUser);
        //删除最爱中关于当前歌曲的信息
        Favorite favorite = new Favorite();
        favorite.setSongId(String.valueOf(songData.getId()));
        favoriteDao.delete(favorite);

        //删除共享歌曲中的当前歌曲关联
        SharedSong sharedSong = new SharedSong();
        sharedSong.setSongId(songData.getId());
        sharedSongDao.delete(new QueryWrapper<SharedSong>().setEntity(sharedSong));

        return rows;
    }


}
